package com.domi.controller;

import com.domi.bean.Book;
import com.domi.bean.RestfulResponse;
import com.domi.bean.RestfulResponse.ResponseCode;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Date;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/book")
public class BookController {

    @GetMapping("/")
    public RestfulResponse index() {
        return RestfulResponse.create(ResponseCode.SUCCESS, "图书管理中心服务, 接口信息见book-center/api.http文件");
    }

    @GetMapping("/search")
    public RestfulResponse search(@RequestParam("q") String qryStr) {
        List<Book> bookList = bookListCache.stream()
                .filter(book -> book.getName().contains(qryStr) || book.getCategory().contains(qryStr))
                .collect(Collectors.toList());
        return RestfulResponse.create(ResponseCode.SUCCESS, bookList);
    }

    @GetMapping("/categories")
    public RestfulResponse categories() {
        Set<String> categorySet = bookListCache.stream()
                .map(book -> book.getCategory().split(","))
                .flatMap(Arrays::stream)
                .collect(Collectors.toCollection(TreeSet::new));
        return RestfulResponse.create(ResponseCode.SUCCESS, categorySet);
    }

    @GetMapping("/info/{id}")
    public RestfulResponse info(@PathVariable Integer id) {
        Optional<Book> bookOptional = bookListCache.stream()
                .filter(book -> book.getId().equals(id))
                .findFirst();
        return bookOptional.map(book -> RestfulResponse.create(ResponseCode.SUCCESS, book))
                .orElse(RestfulResponse.create(ResponseCode.FAIL));
    }

    @GetMapping("/category/{name}")
    public RestfulResponse category(@PathVariable String name) {
        List<Book> bookList = bookListCache.stream()
                .filter(book -> book.getCategory().contains(name))
                .collect(Collectors.toList());
        return RestfulResponse.create(ResponseCode.SUCCESS, bookList);
    }

    @PostMapping("/add")
    public RestfulResponse add(@RequestBody Book book) {
        Optional<Integer> maxIdOptional = bookListCache.stream()
                .map(Book::getId)
                .max(Integer::compareTo);
        Integer newId = maxIdOptional.map(id -> ++id).orElse(1);
        book.setId(newId);
        System.err.println("mock add book: " + book);
        return RestfulResponse.create(ResponseCode.SUCCESS, newId);
    }

    @GetMapping("/flight")
    public RestfulResponse flight() throws InterruptedException {
        int seed = ThreadLocalRandom.current().nextInt(2, 6);
        System.err.println("========= sleep " + seed + " second =========");
        TimeUnit.SECONDS.sleep(seed);
        return RestfulResponse.create(ResponseCode.SUCCESS, "I swim in the sea of books");
    }

    private static final List<Book> bookListCache = Arrays.asList(
            new Book(2214, "疯狂的十万个为什么", 100.00, "崔钟雷", "儿童,科普,启蒙,漫画", "黑龙江美术出版社",
                    Date.valueOf("2022-06-04")),
            new Book(2215, "十万个为什么", 39.00, "阳光三采", "儿童,科普,百科", "青岛出版社",
                    Date.valueOf("2021-03-13")),
            new Book(2216, "我为什么不能", 50.00, "小红帆", "儿童,启蒙,故事", "应急管理出版社",
                    Date.valueOf("2021-05-28")),
            new Book(2217, "一只想飞的猫", 115.0, "陈伯吹", "儿童,启蒙,绘本", "成都地图出版社",
                    Date.valueOf("2022-09-10"))
    );

}